import {
    ILoginAction,
    ILogoutAction,
    loginFailAction,
    loginSuccessAction,
    logoutFailAction,
    logoutSuccessAction
} from "@/stores/actions/loginActions";
import {put, takeEvery} from "redux-saga/effects";
import {login, logout} from "@/services/login";
import {LOGIN, LOGOUT} from "@/stores/actionTypes/loginActionType";
import {GETUSERINFO} from "@/stores/actionTypes/userInfoActionType";

function* handleLogin(action: ILoginAction) {
    try {
        const res = yield login(action.payload)
        yield put(loginSuccessAction(res.data))
        yield put({type: GETUSERINFO})
    } catch (error) {
        console.log(error)
        yield put(loginFailAction(error))
    }
}

function* handleLogout(action: ILogoutAction) {
    try {
        yield logout()
        yield put(logoutSuccessAction())
    } catch (error) {
        yield put(logoutFailAction(error))
    }
}


export function* loginSaga() {
    yield takeEvery(LOGIN, handleLogin)
    yield takeEvery(LOGOUT, handleLogout)
}